"use strict";
$(function () {
    yams.menu.select('productList');

    yams.page = {

        init: function () {
            this.categoryTree();
            this.itemLine();
            this.initEvent();
        },

        initEvent: function () {
            let me = this;
            $("#addProduct").click(function () {
                Dolphin.form.empty('.edit-form');
                let checkedData = me._categoryTree.getChecked();
                if (checkedData.length != 1) {
                    Dolphin.alert('请选择一个模型');
                    return;
                }
                Dolphin.form.setValue({
                    category: {
                        id: checkedData[0].id
                    }
                }, '.edit-form');
                me.renderForm(checkedData[0].id);
                $(".detail-list").empty();
                $('#dataModal').modal('show');
            });
            
            $(".modelSave").click(function () {
                let ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    data['uedit'] = yams.page.um.getContent();
                    if(data.characteristic)
                        data.characteristic = true;
                    Dolphin.ajax({
                        url: '/api/293ff19f7b04482e9adb902893c8a685',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._itemList.load();
                            $('#dataModal').modal('hide');
                        }
                    });

                }
            });
            
            $("#charactInput").change(function () {
                if(this.checked){
                    $('#asset_quantity').attr('disabled',false);
                    $(".genSku").removeClass('hidden');
                } else {
                    $('#asset_quantity').attr('disabled',true);
                    $(".genSku").addClass('hidden');
                }
            });

            $(".genSku").click(function () {
                let n = $("#asset_quantity").val(),rows=[];
                for(let i=0;i<n;i++){
                    rows.push({code:''});
                }
                me._detailItem = me.detailItem('.detail-list',rows,true);
            });
        },

        categoryTree: function () {
            let me = this;
            this._categoryTree = new Dolphin.TREE({
                defaultId: -1,
                requestKey: 'parentId',
                panel: '#categoryTree',
                url: '/api/ac423e9cff8948e4a56adffd88e36e37@parentId={parentId}',
                multiple: false,
                onChecked: function (data) {
                    me.selectNode = data;
                    me._itemList.query({
                        category_id_obj_ae: data.id
                    });
                },
                onLoad: function () {
                    if (this.data && this.data.length > 0)
                        this.expend(this.data[0]);
                }
            });
        },

        itemLine: function () {
            let me = this;
            this._itemList = new Dolphin.LIST({
                panel: '#itemList',
                url: '/api/293ff19f7b04482e9adb902893c8a685',
                ajaxType: 'post',
                mockPathData: ['id'],
                data: {rows: [], total: 0},
                pagination: true,
                multiple: false,
                columns: [{
                    code: 'code',
                    title: '资产编码'
                }, {
                    code: 'name',
                    title: '资产名称'
                }, {
                    code: 'status',
                    title: '状态'
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '100px',
                    formatter: function (val, row, index) {
                        return yams.buttons.edit({
                                id: row.id
                            });
                    }
                }],
                onLoadSuccess: function (data) {
                    yams.buttons.editCallback('f753b87737ca44d6bd5afae34924ada1', 'id', function (reData) {
                        if(reData && reData.value) {
                            if (reData.value['uedit'])
                                yams.page.um.setContent(reData.value['uedit']);
                            if (reData.value.primaryImage) {
                                $("#aImage").attr('src', '/uploadFiles' + reData.value.primaryImage);
                            }
                            me.detailItem('.detail-list',[],true).load('/api/41bddb58728f43af94cea38313c4ccb7@id='+reData.value.id);
                        }
                        $('#dataModal').modal('show');
                    });
                },
                onCheck: function (data, row, thisInput) {
                },
                onChecked: function (data, row, thisCheckbox) {
                    me.curSelect = data;
                },
                onUnchecked: function (data) {
                }
            });
        },
        
        renderForm: function (id, callback) {
            let _this = this;
            Dolphin.ajax({
                url : '/api/047838ba22ff4568ab4b41ab15d7bfc0@cateId={id}',
                mockPathData : ['id'],
                pathData : {
                    id : id
                },
                loading : true,
                onSuccess : function (reData) {
                    _this.categoryAttr = reData.rows;
                    $("#extendStringPanel").empty();
                    $("#extendTextAreaPanel").empty();
                    $("#extendImagePanel").empty();
                    let textareaField = [];
                    let imageField = [];
                    $.each(_this.categoryAttr, function (i, attr) {
                        if(attr.attrType=='string' && attr.arguments && attr.arguments.textType && attr.arguments.textType=='textArea'){
                            attr.textType = 'textArea';
                            textareaField.push(attr);
                        } else if(attr.attrType == 'media') {
                            imageField.push(attr);
                        } else {
                            _this.renderField(attr, $("#extendStringPanel"));
                        }
                    });
                    $.each(textareaField, function (i, attr) {
                        _this.renderField(attr, $("#extendTextAreaPanel"));
                    });
                    if(imageField.length>0){
                    }
                    $.each(imageField, function (i, attr) {
                        _this.renderField(attr, $("#extendImagePanel"));
                    });

                    if(typeof callback == 'function'){
                        callback.call(_this, reData);
                    }
                }
            });
        },

        renderField: function (attr, panel, param) {
            let col, control, inputPanel, input,
                _this = this,
                opts = $.extend({}, param);
            if(typeof opts.eachField === 'function'){
                if(opts.eachField.call(_this, attr) === false){
                    return false;
                }
            }
            if(!attr.display){
                $('<input type="hidden" name="'+attr.attrId+'" />').prependTo(panel);
            }else{
                col = $('<div class="dolphin-col-6">').appendTo(panel);
                control = $('<div class="form-group">').attr({
                    'code': attr.attrCode,
                    'id': attr.attrId
                }).appendTo(col);

                if(attr.attrType != 'media' || attr.attrType != 'richText') {
                    $('<label class="col-md-4 control-label">').html(attr.attrName).appendTo(control);
                    inputPanel = $('<div class="col-md-8">').appendTo(control);
                }
                switch (attr.attrType){
                    case "string":
                        input = $('<' + (attr.textType || 'input') + ' type="text" />');
                        if(attr.defaultValue)
                            input.val(attr.defaultValue);
                        input.attr('name', attr.attrId);
                        break;
                    case "integer":
                    case "number":
                        input = $('<div class="input-group">');
                        $('<input type="text" class="form-control" >').attr({
                            name : attr.attrId
                        }).val(attr.defaultValue?attr.defaultValue:0).appendTo(input);
                        $('<span class="input-group-addon">').html(attr.unitCode || '&nbsp;').appendTo(input);
                        break;
                    case "enum":
                        input = $('<select class="form-control" >');
                        input.attr($.extend({}, {options:attr.enumCode}, attr.param));
                        input.attr('name', attr.attrId);
                        if(attr.defaultValue)
                            input.val(attr.defaultValue);
                        Dolphin.form.parseSelect(input);
                        break;
                    case "image":
                        break;
                    default :
                        input = $('<input type="text" class="form-control" />');
                        input.attr('name', attr.attrId);
                        if(attr.defaultValue)
                            input.val(attr.defaultValue);
                }
                if(input){
                    input.appendTo(inputPanel)
                }
            }
        },

        detailItem: function (panelId, rows, edit) {
            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                columns: [{
                    code: 'code',
                    title: 'SN号'
                }],
                multiple: false,
                rowIndex: false,
                checkbox: false,
                editFlag: edit,
                data: {rows: rows},
                pagination: false,
                editListName: 'skus',
                onClick: function (data, thisRow, event) {

                },
                onRemoveRow: function (data, event, thisRow) {
                    if (thisRow.find('[listName="id"]').val()) {
                        thisRow.remove();
                    }
                }
            });
        }
    };
});